package com.wy.panda.common.model;

import java.io.Serializable;
import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 响应请求数据模型
 * @author wangyuan
 * @since 2019年6月5日 下午5:10:30
 *
 */
@ApiModel("接口通用响应模型")
@Data
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class R<T> implements Serializable {
	
	private static final long serialVersionUID = 182511205688627338L;
	
	public static final int SUCCESS_CODE = 0;
	public static final int ERROR_CODE = 1024;
	
	@ApiModelProperty(value = "状态码")
	private Integer code;
	
	@ApiModelProperty(value = "成功或失败的消息")
	private String msg;
	
	@ApiModelProperty(value = "数据结果集")
	private T data;
	
	@JsonIgnore
	@JSONField(format = "yyyy-MM-dd HH:mm:ss", serialize = false, deserialize = false)
	private Date timestamp;
	
	public static <T> R<T> ok(int code, String msg, T data) {
		return new R<>(code, msg, data, new Date());
	}
	
	public static <T> R<T> ok(int code, String msg) {
		return ok(code, msg, null);
	}
	
	public static <T> R<T> ok(T data) {
		return ok(SUCCESS_CODE, "成功", data);
	}
	
	public static <T> R<T> ok(int code, T data) {
		return ok(code, "成功", data);
	}
	
	public static <T> R<T> ok(String msg, T data) {
		return ok(SUCCESS_CODE, msg, data);
	}
	
	public static <T> R<T> ok() {
		return ok(SUCCESS_CODE, "成功", null);
	}
	
	public static <T> R<T> error(int code, String msg, T data) {
		return new R<>(code, msg, data, new Date());
	}
	
	public static <T> R<T> error() {
		return error(ERROR_CODE, "未知异常，请联系管理员", null);
	}
	
	public static <T> R<T> error(int code, String msg) {
		return error(code, msg, null);
	}
	
	public static <T> R<T> error(int code) {
		return error(code, "未知异常，请联系管理员");
	}
	
	public static <T> R<T> error(String msg) {
		return error(ERROR_CODE, msg);
	}
	
	public static <T> R<T> error(int code, T data) {
		return error(code, "未知异常，请联系管理员", data);
	}
	
	public static <T> R<T> error(String msg, T data) {
		return error(ERROR_CODE, msg, data);
	}
	
	/**
	 * {@link #data}为list时，才可转换
	 * @return
	 */
	public JSONArray dataToJSONArray() {
		Object data = getData();
		if(null == data) {
			return null;
		}
		
		return (JSONArray) JSONArray.toJSON(data);
	}
	
	/**
	 * {@link #data}为Object时，才可转换
	 */
	public JSONObject dataToJSONObject() {
		Object data = getData();
		if(null == data) {
			return null;
		}
		
		return (JSONObject) JSONObject.toJSON(data);
	}
	
	public JSONObject toJSONObject() {
		return (JSONObject) JSONObject.toJSON(this);
	}
	
	public String toJSONString() {
		return JSONObject.toJSONString(this);
	}
}
